import { postApi } from '../request'
import { uploadRequestData } from './types'

//文件上传
export async function uploadFILE(data: uploadRequestData) {
  // 检查文件大小是否在指定范围内
  const fileSizeInBytes = data.file.size;
  const fileSizeInKB = fileSizeInBytes / 1024;
  const fileSizeInMB = fileSizeInKB / 1024;
  if (fileSizeInKB < 10 || fileSizeInMB > 5) {
    console.log('上传文件大小不符合要求！');
    return 'data-0000';
  }

  // 创建一个新的 Image 对象
  const img = new Image();
  img.src = URL.createObjectURL(data.file);
  await new Promise(resolve => img.onload = resolve);

  // 创建一个 canvas 对象并设置其大小
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  canvas.width = img.width;
  canvas.height = img.height;
  if(ctx==null){
    return "error-0000"
  }
  // 将图片绘制到 canvas 上
  ctx.drawImage(img, 0, 0, img.width, img.height);

  // 将 canvas 转换为 Blob 对象
  const blob:any = await new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg', 0.5));

  // 创建一个新的 File 对象
  const file = new File([blob], data.file.name, { type: 'image/jpeg' });

  const formData = new FormData();
  formData.append('file', file);
  try {
    const res = await postApi('file/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    return res;

  } catch (error) {
    console.error(error); // 处理错误
    return "error-0000"
  }
}
